package com.qmds.userserver.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qmds.common.core.entity.User;
import com.qmds.common.core.utils.JwtUtils;
import com.qmds.common.core.vo.R;
import com.qmds.userserver.user.dao.UserMapper;
import com.qmds.userserver.user.param.LoginParam;
import com.qmds.userserver.user.service.LoginService;
import com.qmds.userserver.user.vo.UserVo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * --- 代码敲烂 月薪过万 ---
 *
 * @author ShiJiaWei
 * @date 2024/9/7
 * @desc:
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private UserMapper userMapper;

    @Override
    public R<String> login(LoginParam loginParam) {
        if (loginParam == null) {
            return R.fail("参数错误");
        }
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, loginParam.getUsername()));
        if (user == null) {
            return R.fail("用户不存在");
        }
        if (!user.getPassword().equals(loginParam.getPassword())) {
            return R.fail("用户名和密码错误！");
        }

        Map<String, Object> map = new HashMap<>();
        map.put("uid", user.getId());
        String jwt = JwtUtils.createJwt(map);

        return R.ok("登录成功", jwt);
    }

    @Override
    public R<UserVo> getUserInfo(String token) {
        UserVo userVo = null;
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Integer uid = (Integer) claims.get("uid");
            User user = userMapper.selectById(uid);
            userVo = new UserVo();
            BeanUtils.copyProperties(user, userVo);
        } catch (Exception e) {
            return R.fail("token失效，请重新登录！");
        }
        return R.ok(userVo);
    }


}
